package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SysUserJyjl;
import com.yuncheng.spcyApi.service.ISysUserJyjlService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.PageVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 系统-用户教育经历
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "系统-用户教育经历接口")
@RestController
@RequestMapping("/api/spzx-spcy/sysUserJyjl")
public class SysUserJyjlController extends BaseController<SysUserJyjl, ISysUserJyjlService> {

    private static final Logger log = LoggerFactory.getLogger(SysUserJyjlController.class);

    @Resource
    private ISysUserJyjlService sysUserJyjlService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private IYcSysUserService ycSysUserService;

    @Log(title = "用户教育经历-分页列表查询")
    @ApiOperation(value = "系统-用户教育经历-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SysUserJyjl sysUserJyjl,
                                       @RequestParam(value = "year",defaultValue = "")String year,
                                       @RequestParam(value = "isSelectMe",defaultValue = "true")boolean isSelectMe,
                                       PageVo pageVo,
                                       OrderItemVo orderItemVo) {
        Page<SysUserJyjl> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        if (StringUtils.isNotBlank(sysUserJyjl.getFuserid())){
            isSelectMe = false;
        }
        IPage<SysUserJyjl> pageList = sysUserJyjlService.getPageList(page, sysUserJyjl, year, isSelectMe, orderItemVo);
        return HttpResult.ok(pageList);
    }

    @Log(title = "用户教育经历-所有列表")
    @ApiOperation(value = "用户教育经历-所有列表")
    @GetMapping(value = "/queryAllList")
    public HttpResult<?> queryAllList(SysUserJyjl sysUserJyjl,
                                       @RequestParam(value = "year",defaultValue = "")String year,
                                       @RequestParam(value = "isSelectMe",defaultValue = "true")boolean isSelectMe) {
        if (StringUtils.isNotBlank(sysUserJyjl.getFuserid())){
            isSelectMe = false;
        }
        List<SysUserJyjl> pageList = sysUserJyjlService.getList(sysUserJyjl, year, isSelectMe);
        return HttpResultVo.HttpResultList(pageList);
    }

    @Log(title = "用户教育经历-添加")
    @ApiOperation(value = "系统-用户教育经历-添加")
    @PostMapping(value = "/addJyjl")
    public HttpResult<?> addJyjl(@RequestBody SysUserJyjl sysUserJyjl) {
        sysUserJyjl.setId(GetUuIdUtils.ReplaceUuId());
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已过期，请重新登录");
        }
        if (StringUtils.isBlank(sysUserJyjl.getFuserid())) {
            sysUserJyjl.setFuserid(currentUser.getId());
            sysUserJyjl.setFusermc(currentUser.getName());
        }else {
            YcSysUser user = ycSysUserService.getById(sysUserJyjl.getFuserid());
            if (user != null){
                sysUserJyjl.setFusermc(user.getRealname());
            }
        }

        /*if (StringUtils.isNotEmpty(sysUserJyjl.getFuserid())) {
            sysUserJyjlService.list(new LambdaQueryWrapper<SysUserJyjl>()
                    .eq(SysUserJyjl::getFuserid, sysUserJyjl.getFuserid())
                    .eq(SysUserJyjl::getFbyyx, sysUserJyjl.getFbyyx()));
        }*/

        sysUserJyjlService.save(sysUserJyjl);

        String operContent = "新增信息：";
        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(sysUserJyjl);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JYJL,operContent,sysUserJyjl.getId(), LogConstant.LOGS_SYS_USER_JYJL, SpcyConstant.LOGS_SYS_TYPE_XZ);

        HttpResult result = new HttpResult(true);
        result.setResult(sysUserJyjl);
        result.setMessage("添加成功");
        return result;
    }

    /**
     * 编辑
     *
     * @return
     */
    @Log(title = "系统-用户教育经历-编辑")
    @ApiOperation(value = "系统-用户教育经历-编辑")
    @ApiImplicitParam(name = "id",value = "用户教育经历id",required = true)
    @PutMapping(value = "/editJyjl")
    public HttpResult<?> editJyjl(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("用户教育经历id不能为空");
        }
        String djjxxxId = buffer.get("id");
        SysUserJyjl oldJyjl = sysUserJyjlService.getById(djjxxxId);
        SysUserJyjl oldJyjlUpdate = sysUserJyjlService.getById(djjxxxId);
        if (oldJyjlUpdate == null){
            return HttpResult.error("当前用户教育经历基本信息数据不存在，请重试");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldJyjlUpdate, buffer);
        sysUserJyjlService.updateById(oldJyjlUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldJyjl);
        operContent += LogUtils.BeanModifyMsg(oldJyjlUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JYJL,operContent,djjxxxId,LogConstant.LOGS_SYS_USER_JYJL,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "系统-用户教育经历-批量删除")
    @ApiOperation(value = "系统-用户教育经历-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SysUserJyjl> sysUserJyjls = sysUserJyjlService.listByIds(idsList);
        if (CollectionUtils.isEmpty(sysUserJyjls)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SysUserJyjl jyjl : sysUserJyjls){
            String id = jyjl.getId();
            sysUserJyjlService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(jyjl);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JYJL,operContent,id,LogConstant.LOGS_SYS_USER_JYJL,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "用户教育经历-通过id查询")
    @ApiOperation(value = "用户教育经历-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SysUserJyjl sysUserJyjl = sysUserJyjlService.getById(id);
        return HttpResult.ok(sysUserJyjl);
    }

    /**
     * 导入用户教育经历基本信息数据-表格excel
     */
    @Log(title = "导入用户教育经历基本信息数据-表格excel")
    @ApiOperation(value = "导入用户教育经历基本信息数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
            @ApiImplicitParam(name = "fuserid",value = "用户id",required = true)
    })
    @PostMapping(value = "impJyjlData")
    public HttpResult<?> impJyjlData(@RequestParam(value = "fuserid",defaultValue = "")String userid,@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            log.error("登录过期，导入失败");
            return HttpResult.error("登录失效，请重新登录！");
        }

        String username = "";
        if (StringUtils.isBlank(userid)){
            userid = currentUser.getId();
            username = currentUser.getName();
        }else {
            YcSysUser user = ycSysUserService.getById(userid);
            username = user.getRealname();
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_SYS_JYJL_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入用户教育基本信息数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                SysUserJyjl jyjl = new SysUserJyjl();
                BeanUtil.copyProperties(map,jyjl);
                jyjl.setId(GetUuIdUtils.ReplaceUuId());

                jyjl.setFuserid(userid);
                jyjl.setFusermc(username);
                sysUserJyjlService.save(jyjl);

                String operContent = "新增导入信息：";
                Map<String, Object> bhgzMap = ObjectToMapUtils.objectToMap(jyjl);
                operContent += LogUtils.MapToStringMethod(bhgzMap);
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JYJL,operContent,jyjl.getId(),LogConstant.LOGS_SYS_USER_JYJL,SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    /**
     * 下载用户教育经历-导入模板
     * @param response
     */
    @Log(title = "下载用户教育经历-导入模板")
    @ApiOperation(value = "下载用户教育经历-导入模板")
    @GetMapping("/downUserJyjlTemplate")
    public void downUserJyjlTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("userJyjlImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_SYS_JYJL_XML, out);
        } catch (Exception e) {
            log.error("下载用户教育经历模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出用户教育经历数据-表格excel
     */
    @Log(title = "导出用户教育经历数据-表格excel")
    @ApiOperation(value = "导出用户教育经历数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "id字符逗号分割",dataType = "String"),
            @ApiImplicitParam(name = "fuserid",value = "用户id",required = true),
            @ApiImplicitParam(name = "year",value = "年份",dataType = "String"),
            @ApiImplicitParam(name = "isExportMe",value = "默认导出所有，导入个人值为[是]",dataType = "String")
    })
    @GetMapping("/exportUserGzjlData")
    public void exportUserGzjlData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                   SysUserJyjl jyjl,
                                   @RequestParam(value = "year",defaultValue = "")String year,
                                   @RequestParam(value = "isExportMe",defaultValue = "true")boolean isExportMe,
                                   HttpServletResponse response){
        try {
            String name = "exportUserJyjl";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SysUserJyjl> jyjlList = sysUserJyjlService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(jyjlList)){
                    for (SysUserJyjl e : jyjlList){
                        list.add(e);
                    }
                }
            }else {
                if (StringUtils.isNotBlank(jyjl.getFuserid())){
                    isExportMe = false;
                }
                List<SysUserJyjl> jyjlList = sysUserJyjlService.getList(jyjl, year, isExportMe);
                // 条件导出
                if (CollectionUtils.isNotEmpty(jyjlList)){
                    for (SysUserJyjl e : jyjlList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_SYS_JYJL_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出用户教育经历数据出错-{}",e.getMessage());
        }
    }
}
